package org.example.GirdFind;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.example.bean.Cord;
import org.example.bean.JsonGamePos;

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName FindTest
 * @Description TODO
 * @Author hongjun
 * @Date 2024/5/26 下午6:48
 * @Version 1.0
 */
public class FindTest {
    private static final String CONFIG_DIR = "src/main/resources/MapTilesData.json";

    public static void main(String[] args) throws InterruptedException {
        GameGirdMap gameMap = new GameGirdMap(1200, 1200);
        initMapGridBlockArray(gameMap);
        //gameMap.updateAllGird();
        Random random = new Random();
        //for (int i = 0; i < 10; i++) {
        //int x = random.nextInt(1200);
        //int y = random.nextInt(1200);
        //int x1 = random.nextInt(1200);
        //int y1 = random.nextInt(1200);
        int x = 141;
        int y = 516;
        int x1 = 138;
        int y1 = 493;

        //if (gameMap.isBlocked(x, y) || gameMap.isBlocked(x1, y1)) {
        //    continue;
        //}
        long now = System.currentTimeMillis();
        List<JsonGamePos> pathGird = GirdThetaStarUtil.findPathGird(new JsonGamePos(x, y), new JsonGamePos(x1, y1), gameMap);
        System.out.println("寻路耗时：" + (System.currentTimeMillis() - now));
        if (pathGird == null) {
            System.out.println("寻路失败");
            //画图
            //List<Cord> list = new ArrayList<>();
            //list.add(new Cord(x, y));
            //list.add(new Cord(x1, y1));
            //SwingUtilities.invokeLater(() -> {
            //    GirdMapDrawing gameDraw = new GirdMapDrawing(gameMap, list, "分层寻路");
            //    gameDraw.setVisible(true);
            //});
        } else {
            System.out.println("寻路成功");
            //画图
            List<Cord> list = new ArrayList<>();
            for (JsonGamePos gird : pathGird) {
                list.add(new Cord((int) gird.getX(), (int) gird.getZ()));
            }
            SwingUtilities.invokeLater(() -> {
                GirdMapDrawing gameDraw = new GirdMapDrawing(gameMap, list, "分层寻路");
                gameDraw.setVisible(true);
            });
        }

    }

    /**
     * 生成地图数据
     *
     * @param map
     */
    private static void initMap(GameGirdMap map) {
        String mapJson = getConfigAsString();
        JSONObject jsonObject = JSONObject.parseObject(mapJson);
        Object tilesDatas = jsonObject.get("tilesDatas");
        int max = 0;
        int maxY = 0;
        if (tilesDatas instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) tilesDatas;
            for (Object o : jsonArray) {
                JSONObject tile = (JSONObject) o;
                int value = Integer.parseInt((String) tile.get("_func"));
                if (value != 0) {
                    continue;
                }
                String pos = (String) tile.get("_key");
                List<Integer> integers = convertIdsToIntList(pos, ",");
                Integer x = integers.get(0);
                Integer y = integers.get(1);
                map.addBlock(x, y);
                if (x > max) {
                    max = x;
                }
                if (y > maxY) {
                    maxY = y;
                }
            }
        }
        System.out.println("max:" + max + " maxY:" + maxY);
    }

    /**
     * 初始化格子阻挡
     *
     * @param gameMap
     */
    public static void initMapGridBlockArray(GameGirdMap gameMap) {
        try {
            File file = new File("src/main/resources/Astar0.txt");
            List<String> list = Files.readAllLines(file.toPath());
            for (int i = 0; i < list.size(); i++) {
                String s = takeOutInvisible(list.get(i));
                char[] charArray = s.toCharArray();
                for (int j = 0; j < charArray.length; j++) {
                    char c = charArray[j];
                    if (c != '0') {
                        gameMap.getGirds()[j][i].setStopBlock(true);
                    }
                }
            }
            file = new File("src/main/resources/Astar1.txt");
            list = Files.readAllLines(file.toPath());
            for (int i = 0; i < list.size(); i++) {
                String s = takeOutInvisible(list.get(i));
                char[] charArray = s.toCharArray();
                for (int j = 0; j < charArray.length; j++) {
                    char c = charArray[j];
                    if (c != '0') {
                        gameMap.getGirds()[j + 600][i].setStopBlock(true);
                    }
                }
            }
            file = new File("src/main/resources/Astar2.txt");
            list = Files.readAllLines(file.toPath());
            for (int i = 0; i < list.size(); i++) {
                String s = takeOutInvisible(list.get(i));
                char[] charArray = s.toCharArray();
                for (int j = 0; j < charArray.length; j++) {
                    char c = charArray[j];
                    if (c != '0') {
                        gameMap.getGirds()[j][i + 600].setStopBlock(true);

                    }
                }
            }
            file = new File("src/main/resources/Astar3.txt");
            list = Files.readAllLines(file.toPath());
            for (int i = 0; i < list.size(); i++) {
                String s = takeOutInvisible(list.get(i));
                char[] charArray = s.toCharArray();
                for (int j = 0; j < charArray.length; j++) {
                    char c = charArray[j];
                    if (c != '0') {
                        gameMap.getGirds()[j + 600][i + 600].setStopBlock(true);

                    }
                }
            }
            //logger.info("initMapGridBlockArray end");
        } catch (Exception e) {
            //logger.error(e, e);
        }
    }


    /**
     * 初始化格子阻挡
     *
     * @param maps
     */
    public static void initMapGridBlockArray(int[][] maps) {
        try {
            //logger.info("initMapGridBlockArray start");
            File file = new File("src/main/resources/Astar0.txt");
            List<String> list = Files.readAllLines(file.toPath());
            for (int i = 0; i < list.size(); i++) {
                String s = takeOutInvisible(list.get(i));
                char[] charArray = s.toCharArray();
                for (int j = 0; j < charArray.length; j++) {
                    char c = charArray[j];
                    if (c != '0') {
                        maps[j][i] = 1;
                    }
                }
            }
            file = new File("src/main/resources/Astar1.txt");
            list = Files.readAllLines(file.toPath());
            for (int i = 0; i < list.size(); i++) {
                String s = takeOutInvisible(list.get(i));
                char[] charArray = s.toCharArray();
                for (int j = 0; j < charArray.length; j++) {
                    char c = charArray[j];
                    if (c != '0') {
                        maps[j + 600][i] = 1;
                    }
                }
            }
            file = new File("src/main/resources/Astar2.txt");
            list = Files.readAllLines(file.toPath());
            for (int i = 0; i < list.size(); i++) {
                String s = takeOutInvisible(list.get(i));
                char[] charArray = s.toCharArray();
                for (int j = 0; j < charArray.length; j++) {
                    char c = charArray[j];
                    if (c != '0') {
                        maps[j][i + 600] = 1;
                    }
                }
            }
            file = new File("src/main/resources/Astar3.txt");
            list = Files.readAllLines(file.toPath());
            for (int i = 0; i < list.size(); i++) {
                String s = takeOutInvisible(list.get(i));
                char[] charArray = s.toCharArray();
                for (int j = 0; j < charArray.length; j++) {
                    char c = charArray[j];
                    if (c != '0') {
                        maps[j + 600][i + 600] = 1;
                    }
                }
            }
            //logger.info("initMapGridBlockArray end");
        } catch (Exception e) {
            //logger.error(e, e);
        }
    }

    /**
     * 去掉字符串中的不可见字符
     *
     * @param source
     * @return
     */
    public static String takeOutInvisible(String source) {
        if (null == source || "".equals(source)) {
            return source;
        }

        Matcher m = P1.matcher(source);
        return m.replaceAll("");
    }

    private final static Pattern P1 = Pattern.compile("\\s*|\t|\r|\n");


    /**
     * 读取地图配置
     *
     * @return
     */
    public static String getConfigAsString() {
        String configPath = CONFIG_DIR;
        try {
            byte[] configBytes = Files.readAllBytes(Paths.get(configPath));
            return new String(configBytes);
        } catch (IOException e) {
            e.printStackTrace();
            return "读取异常";
        }
    }

    /**
     * 分割
     *
     * @param ids
     * @param key
     * @return
     */
    public static List<Integer> convertIdsToIntList(String ids, String key) {
        List<Integer> list = new ArrayList<>();
        if (ids == null || ids.length() == 0) {
            return list;
        }
        String[] ps = ids.split(key);
        for (int i = 0; i < ps.length; i++) {
            int id = Integer.parseInt(ps[i]);
            if (id == -1) {
                continue;
            }
            list.add(id);
        }
        return list;
    }
}
